package com.kool.kmqtt.server.packet;

import lombok.Data;

import java.nio.charset.StandardCharsets;

@Data
public class PublishVariableHeader extends VariableHeader {
    /**
     * 主题
     */
    private String topicName;
    /**
     * 报文id
     */
    private Integer packetId;

    public byte[] toBytes() {
        byte[] topicNameBytes = topicName.getBytes(StandardCharsets.UTF_8);
        byte[] topicNameLen = new byte[2];
        topicNameLen[0] = (byte) (topicNameBytes.length >> 8);
        topicNameLen[1] = (byte) (topicNameBytes.length & 0xff);

        //PUBLISH可能没有packetId
        byte[] variableHeaderBytes = packetId == null ? new byte[2 + topicNameBytes.length] : new byte[2 + topicNameBytes.length + 2];
        System.arraycopy(topicNameLen, 0, variableHeaderBytes, 0, 2);
        System.arraycopy(topicNameBytes, 0, variableHeaderBytes, 2, topicNameBytes.length);

        if (packetId != null) {
            byte[] packetIdBytes = new byte[2];
            packetIdBytes[0] = (byte) (packetId >> 8);
            packetIdBytes[1] = (byte) (packetId & 0xff);
            System.arraycopy(packetIdBytes, 0, variableHeaderBytes, 2 + topicNameBytes.length, 2);
        }
        return variableHeaderBytes;
    }
}
